<template>
  <div id="login">
    <router-view></router-view>
    <div class="pageDiv">
      <div class="headerDiv">
        <div class="title">{{ headerTitleString }}</div>
        <div
          class="subTitle"
          v-show="type === 'pwdlogin'"
          @click="gotoRegister"
        >
          立即注册
        </div>
      </div>
      <div class="accountDiv">
        <input
          v-model="phone"
          placeholder="请输入手机号"
          class="account"
          v-show="type !== 'pwdlogin'"
          type="number"
          @blur="fixScroll"
        />
        <img
          :src="deleteimg"
          class="delete"
          v-show="type !== 'pwdlogin' && phone !== ''"
          @click="clearAcount"
        />

        <input
          v-model="account"
          placeholder="请输入手机号"
          class="account"
          v-show="type === 'pwdlogin'"
          type="number"
          @blur="fixScroll"
        />
        <img
          :src="deleteimg"
          class="delete"
          v-show="type === 'pwdlogin' && account !== ''"
          @click="clearAcount"
        />

        <div class="line"></div>
      </div>
      <div class="vcodeDiv">
        <input
          v-model="vcode"
          placeholder="请输入验证码"
          class="pwd"
          v-show="type !== 'pwdlogin'"
          @blur="fixScroll"
        />

        <div
          :class="{
            forgetpwd: true,
            forgetpwdDisable: !phoneRight || this.countDown > 0
          }"
          v-show="type !== 'pwdlogin'"
          @click="getVerifyCode"
        >
          {{ getvcodeTitle }}
        </div>

        <input
          v-model="pwd"
          placeholder="请输入密码"
          class="pwd"
          type="password"
          v-show="type === 'pwdlogin'"
          @blur="fixScroll"
        />
        <div class="forgetpwd" v-show="type === 'pwdlogin'" @click="forgetpwd">
          忘记密码?
        </div>

        <div class="line"></div>
      </div>
      <van-button
        type="default"
        class="loginbutton"
        size="large"
        color="#397BE6"
        @click="loginClick"
        >登录</van-button
      >
      <div class="footDiv">
        <div class="footTopLabel">其他登录方式</div>
        <img :src="loginTypeImg" class="loginImg" @click="changeType" />
        <div class="footBttomLabel">{{ footString }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { Dialog } from "vant";

import {
  api_login,
  api_getVcode,
  api_getwxuserinfo
} from "../../service/api/user";
import { isPhoneNum, md5Str, wxAuthorize } from "../../utils/utils";
import store from "@/store/index";

export default {
  name: "Login",
  data() {
    return {
      // 页面登录类型   codelogin = 验证码登录  pwdlogin = 密码登录 register = 注册 changepwd = 修改密码验证
      type: "pwdlogin",

      deleteimg: require("@/images/icon/login/delete.png"),
      loginTypeImg: require("@/images/icon/login/loginType.png"),

      account: "",
      phone: "",
      pwd: "",
      vcode: "",
      wxCode: this.$route.query.code,
      countDown: 0
    };
  },
  created() {
    let getWXCode;
    let url = window.location.href;
    let start = url.indexOf("code=");
    if (start !== -1) {
      let end = url.indexOf("&");
      if (end > start) {
        getWXCode = url.substring(start + 5, end);
      } else {
        getWXCode = url.substring(start + 5, url.length);
      }
    }
    console.log("getWXCode:" + getWXCode);

    this.wxCode = getWXCode;

    if (this.wxCode) {
      console.log("wxcode = " + this.wxCode);

      // 如果已经有openid了 就不请求了
        if (store.state.wxInfo.openid){return;}

      api_getwxuserinfo(this.wxCode)
        .then(res => {
          console.log(JSON.stringify(res));

          if (res.data.errcode) {
            this.$toast(res.data.errmsg);
          } else {

              if (res.data.subscribe == 0){
                  this.$toast('没有关注公众号');

                  Dialog.alert({
                      title: '未关注公众号',
                      message: '请先关注公众号后再使用'
                  }).then(() => {
                      this.$router.push({name:"home"})
                  });

              } else {
                  this.syncWXUserInfo(res.data);
              }

              console.log( "subscribe= "+ res.data.subscribe);

          }
        })
        .catch(error => {
          this.$toast(error.message);
        });
    } else {
        this.$toast("获取微信code失败");
    }
  },
  computed: {
    // 验证手机号码是否正确
    phoneRight() {
      return /^[1][3,4,5,7,8,9][0-9]{9}$/.test(this.phone);
    },

    footString() {
      if (this.type === "codelogin") return "账号登录";
      return "手机号登录";
    },

    headerTitleString() {
      if (this.type === "changepwd") {
        return "验证手机号";
      } else if (this.type === "register") {
        return "欢迎注册";
      } else {
        if (this.type === "codelogin") {
          return "手机号登录";
        } else {
          return "账号/密码登录";
        }
      }
    },

    getvcodeTitle() {
      if (this.countDown > 0) {
        return this.countDown + "s";
      } else {
        return "获取验证码";
      }
    }
  },
  methods: {
    ...mapActions(["syncUserInfo", "syncWXUserInfo"]),
      fixScroll() {

          let u = navigator.userAgent;

          let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

          if (isiOS) {

              window.scrollTo(0, 0);

          }

      },
    changeType() {
      if (this.type === "codelogin") {
        this.type = "pwdlogin";
      } else if (this.type === "pwdlogin") {
        this.type = "codelogin";
      }
    },

    clearAcount() {
      if (this.type === "changepwd") {
      } else if (this.type === "register") {
      } else if (this.type === "codelogin") {
        this.phone = "";
      } else if (this.type === "pwdlogin") {
        this.account = "";
      }
    },
    // 获取验证码
    async getVerifyCode() {
      if (this.countDown > 0) {
        return;
      }

      // 2.1 过滤
      if (this.phoneRight) {
        this.$toast.loading({
          mask: true,
          message: "",
          duration: 0
        });

        // 2.3 获取短信验证码
          var codeType = 1;

        api_getVcode(this.phone,codeType)
          .then(() => {
            this.$toast("验证码发送成功");
            this.countDown = 60;
            // 2.2 倒计时
            this.intervalId = setInterval(() => {
              this.countDown--;
              if (this.countDown === 0) {
                clearInterval(this.intervalId);
              }
            }, 1000);
          })
          .catch(error => {
            this.$toast(error.message);
          });
      }
    },
    async loginClick() {

        if (process.env.NODE_ENV !== "development") {

            if (
                !store.state.wxInfo.nickname ||
                !store.state.wxInfo.openid ||
                !store.state.wxInfo.headimgurl
            ) {
                this.$toast("获取微信信息有误");
                return;
            }

        }



      if (this.type === "changepwd") {
      } else if (this.type === "register") {
        alert("注册验证");
      } else if (this.type === "codelogin") {
        if (!isPhoneNum(this.phone)) {
          this.$toast("请输入正确的手机号");
          return;
        } else if (this.vcode === "") {
          this.$toast("请输入验证码");
          return;
        } else {
          let s = {
            mobile: this.phone,
            code: this.vcode,
              // nickName: this.phone,
              // openId: "testopenid",
              // avatar: "http://thirdwx.qlogo.cn/mmopen/Q3auHgzwzM4OQtmTTmvAEicknG4POHgt6ZskicuKubH33aZ6xYu7nvCKPeM0ZIG15v3IXe9hDnQMiaslahJHbxaiaA/132"

              nickName: store.state.wxInfo.nickname,
            openId: store.state.wxInfo.openid,
            avatar: store.state.wxInfo.headimgurl
          };
          this.$toast.loading({
            mask: true,
            message: "",
            duration: 0
          });

          api_login(s)
            .then(res => {
              // 用户信息保存到本地
              res.data.nickName = s.nickName;
              res.data.avatar = s.avatar;

              this.syncUserInfo(res.data);

                this.$toast("登录成功");

                this.$router.push({name:"home"});

                // this.$router.back();
            })
            .catch(error => {
              console.log("-------------" + error);

              this.$toast(error.message);
            });
        }
      } else if (this.type === "pwdlogin") {
        if (!isPhoneNum(this.account)) {
          this.$toast("请输入正确的手机号");
          return;
        } else if (this.pwd === "") {
          this.$toast("请输入密码");
          return;
        } else {
            var  s = {};

            if (process.env.NODE_ENV === "development"){

                s = {
                    mobile: this.account,
                    password: md5Str(this.pwd),
                    nickName: "测试用户昵称",
                    openId: "testopenid",
                    avatar: "http://thirdwx.qlogo.cn/mmopen/Q3auHgzwzM4OQtmTTmvAEicknG4POHgt6ZskicuKubH33aZ6xYu7nvCKPeM0ZIG15v3IXe9hDnQMiaslahJHbxaiaA/132"
                    }

            } else {
                    s = {
                        mobile: this.account,
                        password: md5Str(this.pwd),
                        nickName: store.state.wxInfo.nickname,
                        openId: store.state.wxInfo.openid,
                        avatar: store.state.wxInfo.headimgurl
                    }
          };
          this.$toast.loading({
            mask: true,
            message: "",
            duration: 0
          });

          api_login(s)
            .then(res => {
              // 用户信息保存到本地
              res.data.nickName = s.nickName;
              res.data.avatar = s.avatar;
                this.syncUserInfo(res.data);

                this.$toast("登录成功");

                this.$router.push({name:"home"});

                // this.$router.back();
            })
            .catch(error => {

              this.$toast(error.message);
            });
        }
      }
    },
    gotoRegister() {
      // this.$router.push({ path: "/dashboard/login/register/register" });
        this.$router.push({ path: "/register/register" });
    },
    forgetpwd() {
      // this.$router.push({ path: "/dashboard/login/register/changepwd" });
        this.$router.push({ path: "/register/changepwd" });

    }
  }
};
</script>

<style scoped>
#login {
  position: relative;
  top: 0;
  left: 0;
  /*right: 0;*/
  /*bottom: 0;*/
  width: 100%;
  height: 100%;
  z-index: 200;
  overflow: auto;
  background-color: white;
}
.pageDiv {
  margin-left: 1.3333333333333333rem;
  margin-right: 1.3333333333333333rem;

  margin-top: 2.566666666666667rem;
}

.headerDiv {
  display: flex;
  position: relative;
  align-items: center;
  height: 2.8rem;
  width: 100%;
}

.title {
  height: 2.8rem;
  font-size: 2.1333333333333333rem;
  font-family: PingFangSC;
  font-weight: 600;
  color: #121c32;
  line-height: 2.7666666666666666rem;
}
.subTitle {
  position: absolute;
  right: 0rem;
  height: 1.5rem;
  font-size: 1.0666666666666667rem;
  font-family: PingFangSC;
  font-weight: 400;
  color: rgba(57, 123, 230, 1);
  line-height: 1.5rem;
}

.accountDiv {
  position: relative;
  margin-top: 3.7666666666666666rem;
  display: flex;
  height: 3.4rem;
  align-items: center;
}

.account {
  height: 3.4rem;
  width: 20rem;
  line-height: 1.4rem;
}

.delete {
  position: absolute;
  right: 0;
  height: 1rem;
  width: 1rem;
}

.vcodeDiv {
  position: relative;
  margin-top: 0rem;
  display: flex;
  height: 4.4rem;
  align-items: center;
}
.pwd {
  height: 4.4rem;
  width: 15rem;
  line-height: 1.4rem;
}

.forgetpwd {
  position: absolute;
  right: 0;
  height: 4.4rem;
  font-size: 1.0666666666666667rem;
  font-family: PingFangSC;
  font-weight: 400;
  color: rgba(57, 123, 230, 1);
  line-height: 4.4rem;
}

.forgetpwdDisable {
  position: absolute;
  right: 0;
  height: 4.4rem;
  font-size: 1.0666666666666667rem;
  font-family: PingFangSC;
  font-weight: 400;
  color: rgba(191, 195, 205, 1);
  line-height: 4.4rem;
}

.loginbutton {
  margin-top: 2rem;
  border-radius: 1.6333333333333333rem;
}
.footDiv {
  display: flex;
  flex-direction: column;
  height: 6.9rem;
  align-items: center;
  margin-top: 3.2333333333333334rem;
}

.footTopLabel {
  height: 1.2rem;
  font-size: 0.8666666666666667rem;
  font-family: PingFangSC;
  font-weight: 400;
  color: rgba(122, 132, 145, 1);
  line-height: 1.2rem;
}
.footBttomLabel {
  margin-top: 0.36666666666666664rem;
  height: 1.2rem;
  font-size: 0.8666666666666667rem;
  font-family: PingFangSC;
  font-weight: 400;
  color: rgba(18, 28, 50, 1);
  line-height: 1.2rem;
}

.loginImg {
  margin-top: 1.2666666666666666rem;
  height: 2.933333333333333rem;
  width: 2.933333333333333rem;
}

.line {
  position: absolute;
  left: 0rem;
  right: 0rem;
  height: 0.5px;
  bottom: 0rem;
  background-color: #f0f1f5;
}

input::-webkit-input-placeholder {
  font-size: 1.0666666666666667rem;
  font-family: PingFangSC;
  font-weight: 400;
  color: rgba(191, 195, 205, 1);
}
</style>
